package com.crazymakercircle.imClient.handler;


import com.crazymakercircle.im.common.bean.User;
import com.crazymakercircle.im.common.bean.msg.ProtoMsg;
import com.crazymakercircle.im.common.protoBuilder.NotificationMsgBuilder;
import com.crazymakercircle.imClient.client.ClientSession;
import com.crazymakercircle.imClient.protoBuilder.HeartBeatMsgBuilder;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPipeline;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@ChannelHandler.Sharable
@Service("soulTest1ClientHandler")
public class SoulTest1ClientHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    private HeartBeatClientHandler heartBeatClientHandler;

    //在Handler被加入到Pipeline时，开始发送心跳
    @Override
    public void handlerAdded(ChannelHandlerContext ctx)
            throws Exception {

        ProtoMsg.Message message =
                NotificationMsgBuilder.buildNotification(" Netty 灵魂实验 1 " + ctx.channel().id());
        //发送一次消息
        //fixme 此时 isActive 为false，改为连接成功后处理
        sendMessage(ctx, message);
//        ctx.writeAndFlush(message);


    }

    //fixme 网络连接完成后，此处未执行，为什么？
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        super.channelActive(ctx);
//        ProtoMsg.LoginResponse info = pkg.getLoginResponse();
//        ClientSession.loginSuccess(ctx, pkg);
//        new HeartBeatMsgBuilder().buildMsg().getHeartBeat();
        //fixme 心跳 连接成功后，客户端心跳thread
        ChannelPipeline p = ctx.pipeline();
//        在编码器后面，动态插入心跳处理器
        p.addAfter("encoder", "heartbeat", heartBeatClientHandler);

        User user = new User();
        ClientSession session = new ClientSession(ctx.channel());
        HeartBeatMsgBuilder builder =
                new HeartBeatMsgBuilder(user, session);

        ProtoMsg.Message message = builder.buildMsg();
//        heartBeatClientHandler.channelActive(ctx);
        heartBeatClientHandler.heartBeat(ctx, message);
    }

    //连接成功后，发送一次消息
    public void sendMessage(ChannelHandlerContext ctx,
                            ProtoMsg.Message anyMsg) {
        if (ctx.channel().isActive()) {
            log.info("  发送消息 to server");
            ctx.writeAndFlush(anyMsg);
        }
    }

    /**
     * 接受到服务器的心跳回写
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //判断消息实例
        if (null == msg || !(msg instanceof ProtoMsg.Message)) {
            super.channelRead(ctx, msg);
            return;
        }

        //处理消息的内容
        ProtoMsg.Message notificationPkg = (ProtoMsg.Message) msg;

        String json = notificationPkg.getNotification().getJson();

        log.info("{} 服务端的回复： {}", ctx.channel().id(), json);

    }

}
